<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/1/19
 * Time: 下午8:21
 */
namespace app\admin\controller;

use app\common\model\Settings;
use think\Db;
use app\common\model\Message;
class Category extends Common
{
    public function index()
    {
        //设置标题
        $this->templateTitle("商品分类");

        $level = get_category_level();

        //获取所有的一级分类
        $categoryList1 = Db::name("category")
            ->where("is_valid", 1)
            ->where("parent_id", 0)
            ->order("display_order DESC,id DESC")
            ->select();

        if($level>=2){
            //获取所有二级分类
            foreach ($categoryList1 as &$category1)
            {
                $categoryList2 = Db::name("category")
                    ->where("is_valid", 1)
                    ->where("parent_id", $category1["id"])
                    ->order("display_order DESC,id DESC")
                    ->select();

                if($level>=3){
                    //获取三级分类
                    foreach ($categoryList2 as &$category2)
                    {
                        $categoryList3 = Db::name("category")
                            ->where("is_valid", 1)
                            ->where("parent_id", $category2["id"])
                            ->order("display_order DESC,id DESC")
                            ->select();

                        $category2["children"] = $categoryList3;
                    }
                }

                $category1["children"] = $categoryList2;
            }
        }

        $this->assign("list1", $categoryList1);
        $this->assign('level',$level);
        return $this->fetch();
    }

    //添加分类
    public function add()
    {
        //判断是否为添加子分类
        $parentId = request()->has("parent_id")
            ? request()->param("parent_id") : 0;

        //渲染
        if (request()->isGet()) {
            $this->layoutModal();

            //渲染父级对象
            $parent = Db::name("category")
                ->where("id", $parentId)
                ->where("is_valid", 1)
                ->find();

            $this->assign("parent", $parent);

            return $this->fetch();
        }

        //处理
        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "parent_id" => $parentId,
                "is_valid" => 1,
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );
            //分类名称
            $data["title"] = request()->param("title");
            //分类描述
            $data["description"] = request()->param("desc");
            //分类图标
            $data["img_url"] = request()->param("thumb");
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try {


                $categoryId = Db::name("category")->insertGetId($data);
                $log = '添加-分类';
                if ($categoryId) {
                    //获取上级分类
                    $parent = Db::name("category")
                        ->where("id", $parentId)
                        ->where("is_valid", 1)
                        ->find();

                    //ID路径
                    if ($parent) {
                        $data = array(
                            "level" => $parent["level"] + 1,
                            "id_path" => $parent["id_path"] . "-" . $categoryId,
                            "title_path" => $parent["title_path"] . "-" . $data["title"],
                        );
                    } else {
                        $data = array(
                            "level" => 1,
                            "id_path" => "0-" . $categoryId,
                            "title_path" => $data["title"],
                        );
                    }

                    //更新分类ID路径
                    Db::name("category")
                        ->where("id", $categoryId)
                        ->update($data);
                    $log .= '-' . $categoryId;
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log . '成功！');

                } else {
                    Message::admin_log(0, $log);
                    $this->ajaxError($log . '失败');
                }
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //更改分类的可见性
    public function visible()
    {
        if (request()->isAjax())
        {
            //分类ID
            $categoryId = request()->param("cid");
            //获取可见性状态
            $status = request()->param("status");

            try
            {
                //修改分类及其子类的可见性
                $save = Db::name("category")
                    ->where("id", $categoryId)
                    ->setField("is_visible", $status);
                if($status == 1){
                    $log = '设置-分类-'.$categoryId.'-显示';
                }else{
                    $log = '设置-分类-'.$categoryId.'-隐藏';
                }
                if($save){
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log.'成功！');
                }else{
                    Message::admin_log(0, $log);
                    $this->ajaxError($log.'失败');
                }
            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //编辑分类
    public function edit()
    {
        //分类ID
        $categoryId = request()->param("cid");

        if (request()->isGet())
        {
            $this->layoutModal();

            //获取分类信息
            $category = Db::name("category")
                ->alias("c")
                ->join("__CATEGORY__ p", "p.id=c.parent_id", "LEFT")
                ->where("c.id", $categoryId)
                ->field("c.*,p.title AS parent_title")
                ->find();
            $this->assign("category", $category);
            $this->assign("single_image", array("thumb"=>$category["img_url"]));

            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );
            //分类名称
            $data["title"] = request()->param("title");
            //分类描述
            $data["description"] = request()->param("desc");
            //分类图标
            $data["img_url"] = request()->param("thumb");
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try
            {

                //更新分类ID路径
                $save = Db::name("category")
                    ->where("id", $categoryId)
                    ->update($data);
                $log = '编辑-分类-'.$categoryId;
                if($save){
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log.'成功！');

                }else{
                    Message::admin_log(0, $log);
                    $this->ajaxError($log.'失败');
                }
            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }


    //删除分类
    public function remove()
    {
        if (request()->isAjax())
        {
            //获取分类ID
            $categoryId = request()->param("cid");

            try
            {
                $save = Db::name("category")
                    ->where("id", $categoryId)
                    ->setField("is_valid", 0);
                $log = '删除-分类-'.$categoryId;
                if($save){
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log.'成功！');

                }else{
                    Message::admin_log(0, $log);
                    $this->ajaxError($log.'失败');
                }
            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //还原
    public function reduction()
    {
        if (request()->isAjax())
        {
            //获取分类ID
            $categoryId = request()->param("id");

            try
            {
                $save = Db::name("category")
                    ->where("id", $categoryId)
                    ->setField("is_valid", 1);
                $log = '还原-分类-'.$categoryId;
                if($save){
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log.'成功！');

                }else{
                    Message::admin_log(0, $log);
                    $this->ajaxError($log.'失败');
                }
            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //彻底删除
    public function deletes()
    {
        if (request()->isAjax())
        {
            //获取分类ID
            $categoryId = request()->param("id");
            $info = Db::name("category")
                ->where("id", $categoryId)
                ->find();
            try
            {
                $save = Db::name("category")
                    ->where("id", $categoryId)
                    ->delete();

                $log = '彻底删除-分类-'.$categoryId;
                if($save){
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log.'成功！');
                }else{
                    Message::admin_log(0, $log);
                    $this->ajaxError($log.'失败');
                }
            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function recycle()
    {
        if(request()->isGet()){
            //设置标题
            $this->layoutModal();

            //获取所有用户
            $list = Db::name("category")
                ->where('is_valid','neq',1)
                ->paginate(15);

            $this->assign("list", $list);

            return $this->fetch();
        }
    }

}